package com.g2.admin.controller;

import com.g2.admin.common.constant.Constants;
import com.g2.admin.common.constant.RedisConstants;
import com.g2.admin.model.po.UserAccountPo;
import com.g2.admin.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class BaseController {
    @Autowired
    RedisUtil<UserAccountPo> userAccountPoRedisUtil;

    protected HttpSession getSession() {
        return getHttpServletRequest().getSession();
    }

    protected String getSessionId() {
        return getSession().getId();
    }

    protected void invalidate() {
        this.getSession().invalidate();
    }

    protected HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    protected HttpServletResponse getHttpServletResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();
    }

    /**
     * 根据Header的token获取用户账号对象
     *
     * @return
     */
    protected UserAccountPo getUserAccount() {
        return userAccountPoRedisUtil.get(RedisConstants.getKeyToken(getHttpServletRequest().getHeader(Constants.TOKEN_HEADER)));
    }

}
